package com.maxjay.component.simplelist.core;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.log4j.Logger;

import com.maxjay.common.util.cache.CacheUtil;
import com.maxjay.component.simplelist.core.parser.QuerySchemeParser;
import com.maxjay.component.simplelist.model.QueryScheme;
import com.maxjay.system.core.spring.BeanContext;

public class QuerySchemeFatoryImpl implements QuerySchemeFatory {
	
private static final Logger LOG = Logger.getLogger(QuerySchemeFatoryImpl.class);
	
	protected static final String QRY_SCHEME_CACHE_KEY = "querySchemeCache";
	
	private static final String QRY_SCHEME_PARSER_KEY = "querySchemeParser";
	
	protected Cache querySchemeCache = null;
	
	protected BeanContext beanContext;
	
	public QuerySchemeFatoryImpl(BeanContext beanContext) {
		this.beanContext = beanContext;
		querySchemeCache = CacheUtil.getManager().getCache(QRY_SCHEME_CACHE_KEY);
	}

	@Override
	public QueryScheme getQueryScheme(String schemeId) {
		QueryScheme queryScheme = null;
		Element element = querySchemeCache.get(schemeId);
		if(element == null){
			LOG.info("缓存中没有查询方案[" + schemeId + "]，系统重新加载...");
			queryScheme = loadQueryScheme(schemeId);
		}else{
			queryScheme = (QueryScheme)element.getValue();
		}
		return queryScheme;
	}

	@Override
	public QueryScheme loadQueryScheme(String schemeId) {
		querySchemeCache.remove(schemeId);
		QuerySchemeParser querySchemeParser = beanContext.getBean(QRY_SCHEME_PARSER_KEY, QuerySchemeParser.class);
		QueryScheme queryScheme = querySchemeParser.parseQueryScheme(schemeId);
		LOG.info("加载查询方案[" + schemeId + "]");
		querySchemeCache.put(new Element(schemeId, queryScheme));
		return queryScheme;
	}

	@Override
	public boolean isLoadedEntity(String schemeId) {
		Element element = querySchemeCache.get(schemeId);
		if(element == null) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	public void reloadAll() {
		LOG.info("清除查询方案缓存成功...");
		querySchemeCache.removeAll();
	}

	@Override
	public void destroy() {
		LOG.info("销毁查询方案缓存成功...");
		querySchemeCache.dispose();
	}

}
